package couk.mmtdigital.sm.control.commands
{
	import couk.mmtdigital.sm.ApplicationFacade;
	import couk.mmtdigital.sm.model.FileListProxy;
	import couk.mmtdigital.sm.model.UserProxy;
	import couk.mmtdigital.sm.model.vo.LoginVO;
	
	import mx.controls.Alert;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.remoting.RemoteObject;
	
	import org.puremvc.as3.interfaces.ICommand;
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.command.SimpleCommand;

	public class LoginCommand extends SimpleCommand implements ICommand
	{
		private var loginVO:LoginVO;
		private var LoginRO:RemoteObject;
		
		override public function execute(notification:INotification):void{
			loginVO = notification.getBody() as LoginVO;
			trace("user: "+loginVO.username+" pass: "+loginVO.password );
			createRO();
		}
		
		private function createRO():void{
			LoginRO = new RemoteObject();
			LoginRO.destination = "spreadsheetServices";
			LoginRO.source = "sm.UserConfig";
			LoginRO.addEventListener(FaultEvent.FAULT, faultHandler);
			LoginRO.loginUser.addEventListener(ResultEvent.RESULT, resultHandler);
			LoginRO.loginUser(loginVO.username, loginVO.password);
		}
		
		//to catch fault connecting to the gateway
		private function faultHandler(fault:FaultEvent):void
        {
        	trace("code:\n" + fault.fault.faultCode + "\n\nMessage:\n" + fault.fault.faultString + "\n\nDetail:\n" + fault.fault.faultDetail);
        }
        
        private function resultHandler(evt:ResultEvent):void{
        	if(Number(evt.result['valid']) == 1){
            	 var userProxy:UserProxy = facade.retrieveProxy(UserProxy.NAME) as UserProxy;
            	 userProxy.username = evt.result['user']['name'] as String;
            	 userProxy.password = evt.result['user']['pass'] as String;
            	 userProxy.email = evt.result['user']['email'] as String;
            	 userProxy.fileFilter = evt.result['user']['uploadfilter']['type'] as String;
            	 userProxy.fileFilterName = evt.result['user']['uploadfilter']['name'] as String;
            	 
            	 var fileListProxy:FileListProxy = facade.retrieveProxy(FileListProxy.NAME) as FileListProxy;
            	 fileListProxy.currentFile = "upload";
            	 sendNotification(ApplicationFacade.LOGGED); 
        	}else{
        		Alert.show("Check your username and password", "Login Failed");
        	}
        }
	}
}